package org.bluesky.controller;

import org.bluesky.framework.ResponseResult;
import org.bluesky.framework.entity.LoginUser;
import org.bluesky.framework.entity.Menu;
import org.bluesky.framework.entity.User;
import org.bluesky.framework.enums.AppHttpCodeEnum;
import org.bluesky.framework.exception.SystemException;
import org.bluesky.framework.service.LoginAdminService;
import org.bluesky.framework.service.MenuService;
import org.bluesky.framework.service.RoleService;
import org.bluesky.framework.utils.BeanCopyUtils;
import org.bluesky.framework.utils.SecurityUtils;
import org.bluesky.framework.vo.AdminUserInfoVo;
import org.bluesky.framework.vo.MenuVo;
import org.bluesky.framework.vo.RoutersVo;
import org.bluesky.framework.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class LoginController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LoginAdminService loginAdminService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        //必须填写用户名
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginAdminService.login(user);
    }

    @GetMapping("/getInfo")
    public ResponseResult getInfo(){
        //1、获取当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //2、根据用户id查询权限信息
        List<String> perms = menuService.selectPermsByUserId(loginUser.getUser().getId());
        //3、根据用户id1查询角色信息
        List<String> roles = roleService.selectRoleKeyByUserId(loginUser.getUser().getId());
        //4、获取用户信息
        User user = loginUser.getUser();
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        //5、封装返回
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roles,userInfoVo);
        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult getRouters(){
        //查询menu，结果是tree的形式
        Long userId = SecurityUtils.getUserId();
        List<MenuVo> menuVos = menuService.selectRouterMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RoutersVo(menuVos));
    }

    //TODO:退出登录
    @PostMapping("/user/logout")
    public ResponseResult logout(){
        //删除redis中对应的值
        return loginAdminService.logout();
    }
}
